<template>
	<div class="wrap">
		<div class="page-title Menu">
			<h3>日志服务器</h3>
			<div class="addbtn" @click='toAdd()'>
				<img src="../../../img/add.png" />
				<span>添加服务器</span>
			</div>
		</div>
		<!--加载数据-->
	    <loading v-show= '!show'></loading>

	    <transition name="fade"  mode="out-in">
			<div v-show= 'show' class="content">
			<!-- 默认日志服务器 -->
			<div class="server-wrap" v-if="curpage==1">
				<div class="gradient-head" >
					<h3>默认日志服务器</h3>			
				</div>
				<div class="content">
					<ul class="sever-btn" >
						<li v-if="oper!='add'">
							<label class="labels">服务器开关:</label>						    
						    <div class="on_off_but">							
								<button disabled class="btn-active on_but">启用</button>
								<button disabled class="btn-unactive off_but">禁用</button>
							</div>
						</li>						
						<li>
							<label class="labels">服务器地址：</label><span>{{defaultServer.ip}}(本机)</span>				
						</li>
						<li>
				        	<label class="labels">服务器端口：</label><span>{{defaultServer.port}}</span>
				        </li>																		
					</ul>
					<div class="logtype">
						<inputs  :type="'logs'" :disabled="true" :empty="false" :name="defaultServer.types" :val="'1,4,5,6,7,8,9'"  ></inputs>
					</div>
				</div>
			</div>
			<ul class="servers">
				<li class="serve" v-for='(item,index) in tableData' :key="index">
					<div class="server-wrap">
						<div class="gradient-head">
							<h3>日志服务器{{(index+1)+perNum*(curpage-1)}}</h3>			
							<ul class="titile-butn">
								<li @click.stop="editData(item)">
									<img  :src="`/static/${themeColor}-img/bule_sure.png`">															
									<span>确定</span>
								</li>
								<li @click.stop="delModal(item)">
									<img :src="`/static/${themeColor}-img/bule_delet.png`"/>
									<span>删除</span>
								</li>
							</ul>
						</div>
						<loading v-if= "result=='ing'&&edit_id==item.id"></loading>					
						<div class="content"  v-else>
							<ul class="sever-btn" >
								<!--启用禁用 -->
								<li>
									<label class="labels">服务器开关:</label>						    
									<div class="on_off_but">							
										<button @click.stop = "swichStatus(item,1)" :class="[item.switch>0?'btn-active':'btn-unactive']" class="on_but">启用</button>
										<button @click.stop = "swichStatus(item,0)" :class="[item.switch>0?'btn-unactive':'btn-active']" class="off_but">禁用</button>
									</div>
								</li>						
								<!--input-->
								<li>
									<label class="labels">服务器地址：</label>
									<inputs :type="'ipinput'" :empty="false" :name="'ip'" :val="item.ip" :id = "item.id"
									:regex="/^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$/" @getVal="getEditVal" >
									</inputs>
									<span class="mi">* 必填</span>				
								</li>
								<li>
									<label class="labels">服务器端口：</label>
									<inputs :type="'text'" :empty="false" :name="'port'" :val="item.port" 
									:regex="/^([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-5]{2}[0-3][0-5])$/" :id = "item.id" @getVal="getEditVal">
									</inputs>
									<span class="mi">* 必填</span>		
								</li>																		
							</ul>
							<div class="logtype">
								<inputs  :type="'logs'" :empty="false" :name="'types'" :val="item.types" :id = "item.id" :index="index"
								@getVal="getEditVal"></inputs>
							</div>
						</div>						
					</div>
				</li>
			</ul>
			<pagination  :totalNum='count' :nowpage='curpage' :pageSize="pageSize" @curPage ="curPageEvent" @changePageSize="changePageSize"></pagination>					  
			</div>	
		</transition>

		<Modals 
			:id="'modal'" 
			:title="'日志服务器'" 
			:field='field' 
			:collectField = "'id'" 
			:status="result" 
			:errorMsg="errorMsg" 
			:type= "oper" 
			:selectedItems="selected_id"
			:editData ="deldata" 
			:largeMoadl="'width:840px;'" 
			@sentErrorMsg = "getErrorMsg" 	
			@delEvent= 'delData'
			>
			<div slot="add_edit">
				<div class="servers add_servers">
					<ul class="sever-btn" >				
						<li>
							<label class="labels">服务器地址：</label>
							<inputs :type="'ipinput'" :empty="false" :name="'ip'" :val="adddata.ip" 
							:regex="/^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$/" @getVal="getAddVal">
							</inputs>
							<span class="mi">* 必填</span>				
						</li>
						<li>
							<label class="labels">服务器端口：</label>
							<inputs :type="'text'" :empty="false" :name="'port'" :val="adddata.port" 
							:regex="/^([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-5]{2}[0-3][0-5])$/"  @getVal="getAddVal">
							</inputs>
							<span class="mi">* 必填</span>		
						</li>																		
					</ul>
					<div class="logtype">
						<inputs  :type="'logs'" :empty="false" :name="'types'" :val="adddata.types" 
						@getVal="getAddVal"></inputs>
					</div>
				</div>

			</div>
			<div v-if="oper=='add'" slot="modal_footer" >
				 <div class="modal-footer">
					<div v-if = "add_error_notice" style="color:#b63039;text-align: left; ">*{{add_error_msg}}</div>
					<button class="sure-btn button button--aylen" @click="addData(adddata)">确认</button>					
					<button  class="cancel-btn button button--aylen" data-dismiss="modal">取消</button>
				 </div>
			</div>
		</Modals>
		<noticeModal :id="'noticeModal'" :status = "'error'" :errorMsg="'请检查输入格式'">	</noticeModal>
	</div>
</template>
<script>
    let field = [
        {
            type:'ipinput', 
						label:'服务器地址',
            name:'ip',
            regex:/^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$/,
            requried:true, 
            remark:'*必填'
        },
        {
            type:'text',
            label:'服务器端口',
            name:'port',
            regex:/^([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-5]{2}[0-3][0-5])$/,
            requried:true, 
            remark:'*必填'
        },
        {
            type:'logs',
            label:'日志类型',
            name:'types',
            regex:null,
            requried:true, 
            remark:'*必选，至少选择一种'    
        },
    ]
  import loading from 'components/common/loading'	
	import Modals from 'components/common/Modals'	
	import noticeModal from 'components/common/noticeModal'
	import inputs from 'components/common/inputs'
	import pagination from 'components/common/pagination'
	import logManageService from 'services/logManageService'
	export default {
		components: {
			inputs,
			Modals,
			noticeModal,
			loading,
			pagination
		},
		data() {
			return {
				field:field,
				tableData: [],
				oper: '',
				result: '',
				modok: '',
				operID: '',
				errorMsg: '',
				switch: '',
				show:false,
				defaultServer:{},
				adddata:{
					switch:0,
					ip:'',
					port:'',
					types:''
				},
				add_format_error:[],
				add_error_notice:"",
				deldata:{},
				selected_id:[],
				editdata:{},
				edit_id:'',
				edit_format_obj:{},
				count:1,
				curpage:1,
				perNum:2,
				pageSize:[ 2 , 3 , 5],
			}
		},
		mounted() {
			this.getData()			
		},
		watch:{
			tableData:function(){
				// edit_format_obj = {0:[],2:[]}
				// editdata_item = {0:{},2:{}}
				for(let [k,v] of this.tableData.entries()){
					let err_arr_item = {[v.id]:[]}
					Object.assign(	this.edit_format_obj,err_arr_item)
					let editdata_item =  {
						[v.id]:{
								id:v.id,
								switch:v.switch,
								ip:v.ip,
								port:v.port,
								types:v.types
						}
					}
					Object.assign(this.editdata,editdata_item)
				}
			}
		},
		methods: {
			getErrorMsg(msg) {
        this.errorMsg = msg
			},
			changePageSize (pageSize) {
				this.perNum = pageSize
				let totalPage =  Math.ceil(this.totalNum / pageSize)
				if (totalPage < this.curpage){
					if (totalPage === 0) {
						this.curPage = 1
					} else {
						this.curpage = totalPage
					}
				}
				this.getData()
			},
			curPageEvent(cur_page){
				this.curpage = cur_page
				this.getData()
			},
			getData() {					   
				logManageService.getServer(this.curpage,this.perNum)
				.then((res) => {				
					this.show = true
					if (res.errcode === 0) {
						this.result = 'ok'
						if(this.curpage===1){//默认服务器
							this.defaultServer = res['7'].data.splice(0,1)[0]
						}						
						this.tableData = res['7'].data
						this.count = res['7'].count
					} else {
						this.result = 'error'
						this.errorMsg = String(res.errorMessage)
					}
				})	
			},
			toAdd() {
				this.oper = 'add'				
				this.reset()
				$("#modal").modal("show")
			},
			getAddVal(name,val,format_test,id) {//接收inputs发送回来的值	
				this.adddata[name] = val	
				if (format_test) { 
                    this.error_notice = false
                    for(let [index,ele] of this.add_format_error.entries()) {
                        if (ele == name) {
                            this.add_format_error.splice(index,1)
                        }
                    }
                } else {
                    let format_error_arr = new Set([...this.add_format_error,name])
                    this.add_format_error = [...format_error_arr]
                } 
            }, 
			addData(params){
				params.switch = 1
				let test = this.addTestVal(params)
				if(!test){
					return
				}
				
				let conf = `${params.ip}|${params.port}|${params.switch}|${params.types}`
				this.result = 'ing'
				logManageService.addServer(conf)
				.then((res) => {				
					if (res.errcode === 0) {
						this.result = 'ok'
						$("#modal").modal('hide')
						this.getData()
					} else {
						this.result = 'error'
						this.errorMsg = String(res.errorMessage)
					}
				})	
			},
			addTestVal(params) {	
        for(let i = 0; i < this.field.length; i++) {			                         
					let val = params[this.field[i].name]					
					let label = this.field[i].label
					let format_error = false
					for(let [index,ele] of this.add_format_error.entries()) {
						if (ele == this.field[i].name) {
							format_error = true
						}
					}

					if (!val&&this.field[i].requried) {
						this.add_error_notice = true
						this.add_error_msg = label+"为必填项，请输入（选择）"+label+"!"
						return false
					} else if (format_error) {
						this.add_error_notice = true
						this.add_error_msg = label+"格式错误!"
						return false
					} else {
						this.add_error_notice = false   	
					}    
					}
						return true             
			}, 	
			delModal(deldata) {
				this.oper = "del"
				this.deldata = deldata
				this.selected_id = [deldata.id]
				this.reset()
				$('#modal').modal('show')
			},
			delData(ids){
				this.result = 'ing'
				logManageService.delServer(ids.id)
				.then((res) => {				
					if (res.errcode === 0) {
						this.result = 'ok'
						$("#modal").modal('hide')
						this.getData()
					} else {
						this.result = 'error'
						this.errorMsg = String(res.errorMessage)
					}
				})	
			},
			getEditVal(name,val,format_test,id) {//接收inputs发送回来的值	
				this.editdata[id][name] = val

				if (format_test) { 
						this.error_notice = false
						for(let [index,ele] of this.edit_format_obj[id].entries()) {
								if (ele == name) {
										this.edit_format_obj[id].splice(index,1)
								}
						}
				} else {
						let edit_format_obj = new Set([...this.edit_format_obj[id],name])
						this.edit_format_obj[id] = [...edit_format_obj]
				} 		
			},
			editData(Item){
				this.edit_id = Item.id
				let test = true
				if(this.edit_format_obj[Item.id]){
					test = 	this.edit_format_obj[Item.id].length===0?true:false
				}		
				if(!test){
					$('#noticeModal').modal('show')
					return
				}

				let params = this.editdata[Item.id]
				let conf = `${params.id}|${params.ip}|${params.port}|${params.switch}|${params.types}`
				this.result = 'ing'
				logManageService.editServer(conf)
				.then((res) => {				
					if (res.errcode === 0) {
						this.result = 'ok'
						$("#modal").modal('hide')
						this.getData()
					} else {
						this.result = 'error'
						this.errorMsg = String(res.errorMessage)
					}
				})	
			},
			swichStatus(Item,on_off) {
				this.edit_id = Item.id	
				if (Item.switch!=on_off) {
					this.editdata = {
						id:Item.id,
						switch:on_off,
						ip:Item.ip,
						port:Item.port,
						types:Item.types
					}					
					this.editData(this.editdata)
				}
			},
			reset() {
				this.result = ''
				this.errorMsg = ''
			}
		}
	}
</script>
<style scoped lang="less">
	.wrap {
		margin: 30px 0 0 30px;
		background: #ffffff;
		padding-bottom: 10px;
	}
	.addbtn {
		float: right;
		margin-right: 15px;
		cursor: pointer;
	}
	.sever-btn{
		display: flex;
		justify-content: space-between;
		li{
			margin-top: 15px;
			margin-bottom: 15px;
			
		}
		li:nth-child(2){
			width: 340px;
		}
		li:nth-child(3){
			width: 320px;
		}
	}
	.add_servers{
		text-align: left;
		border: 1px solid #E0E0E0;
	}
	.server-wrap{
		margin: 20px 0;
		border: 1px solid #E0E0E0;
	}
	p {
		text-align: center;
		line-height: 500px;
		font-size: 16px;
	}
	.content{
		padding: 0 20px;
	}
</style>